package com.skivingcloud.report.ureport.controller;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bstek.ureport.export.ExportManager;
import com.skivingcloud.admin.sys.entity.User;
import com.skivingcloud.admin.utils.UserUtil;
import com.skivingcloud.common.exception.BusinessException;
import com.skivingcloud.common.utils.PageUtils;
import com.skivingcloud.common.utils.R;
import com.skivingcloud.common.utils.StringUtils;
import com.skivingcloud.report.ureport.entity.UreportFileTbl;
import com.skivingcloud.report.ureport.service.IUreportFileTblService;

import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author skivingcloud
 * @since 2022-03-03
 */
@RestController
@RequestMapping("/ureportc/filetbl")
public class UreportFileTblController {
	
	private static Logger log = LoggerFactory.getLogger(UreportFileTblController.class);

	@Autowired
	private ExportManager exportManager;
	@Autowired
	private IUreportFileTblService ureportFileTblService;
	
	/**
	 * 分页查询
	 * 
	 * @param params
	 * @return
	 */
	@PostMapping("/list")
	public R list(@RequestBody Map<String, Object> params) {
		try {
			PageUtils page = ureportFileTblService.queryPage(params);
			return R.ok().put("page", page);
		} catch (Exception e) {
			log.error("查询文件列表失败list", e);
			return R.error("查询文件列表失败");
		}
	}
	
	/**
	 * 文件上传，使用formData.append('file', val.raw)来上传文件
	 * 
	 * @param request
	 * @return
	 */
	@PostMapping("/importReport")
	public R importReport(HttpServletRequest request) {
		try {
			User user = UserUtil.getUser();
			StandardServletMultipartResolver resolver = new StandardServletMultipartResolver();
			MultipartHttpServletRequest mhr = resolver.resolveMultipart(request);
			List<MultipartFile> files = mhr.getFiles("file");
			for (MultipartFile file : files) {
				String name = file.getOriginalFilename();
				String extension = FilenameUtils.getExtension(name);
				if (StringUtils.isNotBlank(extension) && extension.equals("xml")) {
					InputStream fileInputStream = null;
					BufferedReader br = null;
					fileInputStream = file.getInputStream();
					br = new BufferedReader(new InputStreamReader(fileInputStream));
					StringBuilder sb = new StringBuilder();
					String line;
					while ((line = br.readLine()) != null) {
						sb.append(line);
					}
					ureportFileTblService.addOrUpdateUreportFileTbl(name, sb.toString());

				} else {
					throw new BusinessException("不支持的文件类型：" + extension);
				}
			}
			return R.ok();
		} catch (Exception e) {
			log.error("上传文件失败", e);
			return R.error("上传文件失败");
		}
	}

	/**
	 * 文件下载
	 * 
	 * @param id       文件记录id
	 * @param response
	 * @return
	 */
	@RequestMapping("/downloadFile/{id}")
	public String downloadFile(@PathVariable("id") String id, HttpServletResponse response) {
		UreportFileTbl ureportFileTbl = ureportFileTblService.getById(id);
		if (ureportFileTbl == null) {
			return "文件丢失";
		}
		OutputStream outputStream = null;
		ByteArrayInputStream bis = null;
		try {
			outputStream = response.getOutputStream();
			byte[] bytes = ureportFileTbl.getContent().getBytes();
			bis = new ByteArrayInputStream(bytes);
			byte[] b = new byte[1024];
			int len = -1;
			response.setHeader("content-type", "application/octet-stream");
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition",
					"attchement;filename=" + URLEncoder.encode(ureportFileTbl.getName(), "UTF-8"));
			while ((len = bis.read(b, 0, 1024)) != -1) {
				outputStream.write(b, 0, len);
			}
		} catch (Exception e) {
			log.error("下载文件失败", e);
			return "下载文件失败";
		} finally {
			if (outputStream != null) {
				try {
					outputStream.flush();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (bis != null) {
				try {
					bis.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	/**
	 * 批量删除文件
	 * 
	 * @param ids
	 * @return
	 */
	@PostMapping("/delete")
	public R delete(@RequestBody String[] ids) {
		try {
			ureportFileTblService.delete(ids);
			return R.ok();
		} catch (Exception e) {
			log.error("删除文件失败delete", e);
			return R.error("删除文件失败");
		}
	}
}
